#include "bencode.h"
#include <stdio.h>
#include <stdlib.h>

char* filename;
	
void printNode(be_node *node){
	if (node->type==BE_STR){
		// print it in HTML as a paragraph
		printf("<p>%s</p>\n", node->val.s);
	} else if (node->type==BE_INT){
		// print it in HTML as an input
		printf("<span>%li</span>\n", node->val.i);
	} else if (node->type==BE_LIST){
		// print it in HTML as an ordered list
		int i;
		
		printf("<ol>\n");
		
		for (i = 0; node->val.l[i]; ++i) {
			printf("<li>\n");
			printNode(node->val.l[i]);
			printf("</li>\n");
		}

		/*length = sizeof(node->val.l)/sizeof(be_node*);
		
		for(i=0; i<length; i++){
			printNode(node->val.l[i]);
		}*/

		printf("</ol>\n");
	} else if (node->type==BE_DICT){
		// print it in HTML as a table
		int i;
		printf("<table>\n");
		
		for (i = 0; node->val.d[i].val; ++i) {
			printf("<tr>\n<td>%s</td>\n<td>\n", node->val.d[i].key);
			printNode(node->val.d[i].val);
			printf("</td>\n</tr>\n");
		}
		printf("</table>\n");
	}
}

void handleFile(FILE *fp, int size){
	char buffer[size];
	
	fgets(buffer, size, fp);
	printf("<html>\n");
	printf("<head>\n");
	printf("<title>Export van: %s</title>\n", filename);
	printf("<link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\" />\n");
	printf("</head>\n");
	printf("<body>\n");
	printNode(be_decode(buffer));
	printf("</body>\n");
	printf("</html>\n");
}

void readFile(char* filename){
	FILE *fp;
	int size;
	
	fp = fopen ( filename, "r" ) ;
	
	if (fp==NULL){
		printf("File %s doesn't exists!\n", filename);
		exit(0);
	}
	
	fseek(fp, 0, SEEK_END); // seek to end of file
	size = ftell(fp)/sizeof(char); // get current file pointer
	fseek(fp, 0, SEEK_SET); // seek back to beginning of file
	printf("Size: %d chars\n", size);
	
	handleFile(fp, size);
	fclose(fp);
}

int main(int argc, char *argv[]){
	if (argc==1){
		printf("Usage: ./as3_t2 <filename>\n");
		exit(0);
	} else{
		filename = argv[1];
		readFile(filename);
		//handleFile();
		// closeFile();
	}
	
	return 0;
}




